import React, { useState } from 'react';
import { Upload, message, UploadProps, Spin } from 'antd';
import { AssetAcquisitionManageAPI } from '../common/type';
import cls from 'classnames';
import { InboxOutlined } from '@ant-design/icons';
import { downloadTemplate, fieldFlowExport, getTenant } from '@/utils';
import { exportEnterService } from '../services';
import moment from 'moment';
import { getRequestIp } from '../../Acommon';
import { getBaseUrl } from '@/services/urlconst';
import { useRequest } from 'umi';
const baseUrl = getRequestIp();

export const UploadFirstStep: React.FC<AssetAcquisitionManageAPI.IFirstStepUpload> = ({
  curRes,
  prefix,
  current,
  reloadUploadList,
  isNowCheckPeople,
  detailInfo,
  modalState,
  downLoadData,
  onUploadCancel,
  reloadManage,
  setDetailId,
}) => {
  const [downLoading, setDownLoading] = useState<boolean>(false);

  const [upLoading, setUpLoading] = useState<boolean>(false);

  const onSetUploadInfo = (info: any) => {
    if (info) {
      reloadUploadList(info);
    }
  };

  const onResetUpload = () => {
    reloadUploadList([]);
  };

  /* 上传 */
  const uploadProps: UploadProps = {
    accept: '.xls,.xlsx',
    headers: {
      tenantName: getTenant(),
    },
    name: 'attachFile',
    maxCount: 1,
    action: `${baseUrl}/assetStorage/import?materialType=${downLoadData?.materialType}&storageId=${modalState?.storageId || ''}`,
    onChange(info) {
      if (info.file.status == 'uploading') {
        setUpLoading(true);
      }
      if (info.file.status === 'done') {
        if (info.file?.response) {
          if (info.file?.response?.msgFlag) {
            message.success(`${info.file.name} 上传成功`);
            if (info.file?.response?.obj) {
              onUploadCancel();
              setDetailId(info.file?.response?.obj);
              reloadManage();
              // info.file?.response?.obj.map((item, index) => {
              //   item.rowId = `${new Date().getTime()}${index}`;
              //   return item;
              // });
              // onSetUploadInfo(info.file?.response?.obj);
            }
            setUpLoading(false);
          } else {
            message.error(<pre>{info.file?.response?.msg || '导入失败'}</pre>);
            setUpLoading(false);
          }
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
        onResetUpload();
        setUpLoading(false);
      }
    },
    onRemove: (file) => {
      if (file) {
        onResetUpload();
      }
    },
  };

  const downLoadCall = () => {
    setDownLoading(false);
  };

  // const importTemplate = () => {
  //   setDownLoading(true);
  //   const date = moment().format('YYYYMMDDhhmmss');
  //   const url = '/materialController/downloadFile';
  //   const title = `物料模板${date}.xlsx`;
  //   const filePath = '/minfile/purchase/template/wlmb.xlsx';
  //   downloadTemplate(url, title, filePath, downLoadCall);
  // };

  /** 导出回调 */
  const exportCallback = (res: any) => {
    const date = moment().format('YYYYMMDDhhmmss');
    /** 处理文件流 */
    //type 资产1 材料0
    fieldFlowExport(res, `${modalState?.type == '1' ? '资产' : '材料'}入库登记模板${date}.xlsx`);
  };

  const { exportEnterRun, exportEnterLoading } = exportEnterService(exportCallback, modalState);

  // 点击下载模板
  const handleDownFile = () => {
    const params: any = { ...downLoadData };
    // if (isNowCheckPeople) {
    params.id = detailInfo?.id || ''; // 主数据id
    params.applyStorageId = detailInfo?.applyStorageId || ''; // 合同id
    // }

    exportEnterRun(params);
  };

  /** 物料模板下载 */
  const materialTempDown = () => {
    message.success('下载中，请稍后...');
    const date = moment().format('YYYYMMDDhhmmss');
    let DownloadLink = document.createElement('a');
    DownloadLink.href = `${getBaseUrl()}/assetStorage/easyExcelExport`;
    DownloadLink.download = `入库登记模板${date}.xlsx`;
    document.body.appendChild(DownloadLink);
    DownloadLink.click(); // 触发a标签的click事件
    document.body.removeChild(DownloadLink);
  };

  return (
    <div className={cls(prefix + 'content-body')} style={{ display: current === 0 ? 'block' : 'none' }}>
      <Spin spinning={upLoading || exportEnterLoading}>
        <div className={prefix + 'download'} style={{ width: '100%' }}>
          <Upload.Dragger {...uploadProps} className={prefix + 'dragger'} style={{ width: '100%' }}>
            <div style={{ height: 'auto' }}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <div className={prefix + 'upload-text'}>
                将文件拖到此处，或&nbsp;
                <span className={prefix + 'upload-text-click'}>点击上传</span>
              </div>
            </div>
          </Upload.Dragger>
          <div className={prefix + 'tip-title'} slot="tip">
            • 文件格式保证正确（仅支持.xlsx .xls文件）
            <span className={prefix + 'download-tem'} onClick={handleDownFile}>
              {isNowCheckPeople ? '原始数据导出' : '下载模板'}
            </span>
            {!isNowCheckPeople && <p style={{ color: 'red' }}> • 请仔细阅读模板中的填写说明</p>}
            {/* <a className={prefix + 'download-tem'} onClick={exportEnterRun}>
              下载模板
            </a> */}
          </div>
        </div>

        {/* <div className="tip_title" slot="tip">
          • 单个文件不能超过100MB
        </div> */}

        {/* <div className={prefix + 'card'}>
          <div className={cls(prefix + 'card-icon')}>
            <MyIcon type={'icon-download1'} />
          </div>
          <div className={cls(prefix + 'card-info')}>
            <div className={cls(prefix + 'card-info-title')}>{'物料模板' ?? ''}</div>
            <div className={cls(prefix + 'card-info-describe')}>{'请先下载物料模板' ?? ''}</div>
            <div className={cls(prefix + 'card-info-download')}>
              <Button
                icon={<DownloadOutlined />}
                type={'link'}
                size={'small'}
                loading={downLoading}
                onClick={() => {
                  setDownLoading(true);
                  const date = moment().format('YYYYMMDDhhmmss');
                  const url = '/materialController/downloadFile';
                  const title = `物料模板${date}.xlsx`;
                  const filePath = '/hrky/file/purchase/template/wlmb.xlsx';
                  downloadTemplate(url, title, filePath, downLoadCall);
                }}
              >
                下载模板
              </Button>
            </div>
          </div>
        </div> */}
        {/* <div className={cls(prefix + 'card')}>
          <div className={cls(prefix + 'card-icon')}>
            <MyIcon type={'icon-upload1'} />
          </div>
          <div className={cls(prefix + 'card-info')}>
            <div className={cls(prefix + 'card-info-title')}>{'上传文件' ?? ''}</div>
            <div className={cls(prefix + 'card-info-describe')}>{'请将文件放置其中' ?? ''}</div>
            <div className={cls(prefix + 'card-info-download')}>
              <Upload {...uploadProps} className={'download'}>
                <Button icon={<UploadOutlined />} type={'link'} size={'small'}>
                  上传文件
                </Button>
              </Upload>
            </div>
          </div>
        </div> */}
      </Spin>
    </div>
  );
};
